﻿using System;
using System.Web.Mvc;

using MarkdownSharp;

using mvcForum.Web.Interfaces;
using mvcForum.Core.Interfaces.AddOns;
using mvcForum.AddOns.ContentParsing.MarkDown;

namespace mvcForum.AddOns.ContentParsing {

	public class MarkDownParser : IContentParser {
		private readonly MarkDownConfiguration config;

		public MarkDownParser(MarkDownConfiguration config) {
			this.config = config;
		}

		public MvcHtmlString Parse(String content) {
			String quoteBefore = "<div class=\"ca-bbcode\"><div class=\"ca-bbcode2 ca-quote\"><blockquote><div>";
			String quoteAfter = "</div></blockquote></div></div>";
			if (!String.IsNullOrWhiteSpace(this.config.QuoteBefore)) {
				quoteBefore = this.config.QuoteBefore;
			}
			if (!String.IsNullOrWhiteSpace(this.config.QuoteAfter)) {
				quoteAfter = this.config.QuoteAfter;
			}
			String paragraphBefore = "<p>";
			String paragraphAfter = "</p>";
			if (!String.IsNullOrWhiteSpace(this.config.ParagraphBefore)) {
				paragraphBefore = this.config.ParagraphBefore;
			}
			if (!String.IsNullOrWhiteSpace(this.config.ParagraphAfter)) {
				paragraphAfter = this.config.ParagraphAfter;
			}
			String codeBefore = "<div class=\"ca-bbcode\"><div class=\"ca-bbcode2 ca-code\"><dl class=\"codebox\"><dt>Code:</dt><dd><code>";
			String codeAfter = "</code></dd></dl></div></div>";
			if (!String.IsNullOrWhiteSpace(this.config.CodeBefore)) {
				codeBefore = this.config.CodeBefore;
			}
			if (!String.IsNullOrWhiteSpace(this.config.CodeAfter)) {
				codeAfter = this.config.CodeAfter;
			}

			Markdown md = new Markdown(new[] { 
						new MarkDownTag("quote", quoteBefore, quoteAfter),
						new MarkDownTag("paragraph", paragraphBefore, paragraphAfter),
						new MarkDownTag("code", codeBefore, codeAfter)
					});

			// Let's sanitize the input, we only want allowed HTML-tags to get past the parser and into the output!
			return MvcHtmlString.Create(md.Transform(content.SanitizeHTML(new String[] { "script" })));
		}

		public String Quote(String author, String content) {
			String quote = "> <cite>{0} wrote:</cite> {1}";
			if (!String.IsNullOrWhiteSpace(this.config.Quote)) {
				quote = this.config.Quote;
			}
			return String.Format(quote, author, content);
		}

		public String Name {
			get {
				return "MarkDown";
			}
		}
	}
}